<template>
  <div class="category-list">
    <a-card :bordered="false">
      <template #title>
        <span>维修类别管理</span>
        <a-tag color="blue" style="margin-left: 8px;">
          共 {{ dataSource.length }} 条
        </a-tag>
      </template>

      <template #extra>
        <a-space>
          <a-button
            type="primary"
            :icon="h(PlusOutlined)"
            @click="showCreateModal"
          >
            新增类别
          </a-button>
          <a-button :icon="h(ReloadOutlined)" @click="fetchData">
            刷新
          </a-button>
        </a-space>
      </template>

      <!-- 搜索表单 -->
      <div class="search-form" style="margin-bottom: 16px;">
        <a-form layout="inline" :model="searchForm">
          <a-form-item label="类别名称">
            <a-input
              v-model:value="searchForm.categoryName"
              placeholder="请输入类别名称"
              style="width: 160px;"
              allow-clear
            />
          </a-form-item>
          <a-form-item label="状态">
            <a-select
              v-model:value="searchForm.isActive"
              placeholder="请选择状态"
              style="width: 120px;"
              allow-clear
            >
              <a-select-option :value="1">启用</a-select-option>
              <a-select-option :value="0">禁用</a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item>
            <a-space>
              <a-button type="primary" @click="handleSearch">
                搜索
              </a-button>
              <a-button @click="resetSearch">
                重置
              </a-button>
            </a-space>
          </a-form-item>
        </a-form>
      </div>

      <a-table
        :columns="columns"
        :data-source="dataSource"
        :loading="loading"
        :pagination="pagination"
        :locale="{ emptyText: '暂无数据' }"
        @change="handleTableChange"
        :scroll="{ x: 1200, y: 800 }"
        row-key="id"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'isActive'">
            <a-tag :color="record.isActive ? 'green' : 'red'">
              {{ record.isActive ? '启用' : '禁用' }}
            </a-tag>
          </template>

          <template v-if="column.key === 'createdAt'">
            {{ formatDate(record.createdAt) }}
          </template>

          <template v-if="column.key === 'action'">
            <a-space>
              <a-button
                type="link"
                size="small"
                @click="showEditModal(record)"
              >
                编辑
              </a-button>
              <a-button
                type="link"
                size="small"
                danger
                @click="handleDelete(record)"
              >
                删除
              </a-button>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>

    <!-- 新增/编辑类别弹窗 -->
    <a-modal
      v-model:open="modalVisible"
      :title="isEdit ? '编辑类别' : '新增类别'"
      @ok="handleSubmit"
      :confirm-loading="submitLoading"
    >
      <a-form
        ref="formRef"
        :model="form"
        :rules="rules"
        layout="vertical"
      >
        <a-form-item label="类别名称" name="categoryName" required>
          <a-input
            v-model:value="form.categoryName"
            placeholder="请输入类别名称"
          />
        </a-form-item>

        <a-form-item label="类别描述" name="description">
          <a-textarea
            v-model:value="form.description"
            placeholder="请输入类别描述"
            :rows="3"
          />
        </a-form-item>

        <a-form-item label="状态" name="isActive">
          <a-radio-group v-model:value="form.isActive">
            <a-radio :value="1">启用</a-radio>
            <a-radio :value="0">禁用</a-radio>
          </a-radio-group>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, h } from 'vue'
import { message, Modal } from 'ant-design-vue'
import { useUserStore } from '@/stores/user'
import { useAppStore } from '@/stores/app'
import { getCategoryList, createCategory, updateCategory, deleteCategory } from '@/api/category'
import type {
  RepairCategory,
  RepairCategoryAddRequest,
  RepairCategoryUpdateRequest,
  PageResponse,
  PaginationState,
  RepairCategoryQueryRequest
} from '@/types'
import { createPaginationFromResponse, handlePaginationNavigation } from '@/utils/pagination'
import type { FormInstance } from 'ant-design-vue'
import type { Rule } from 'ant-design-vue/es/form'
import {
  PlusOutlined,
  ReloadOutlined
} from '@ant-design/icons-vue'

const userStore = useUserStore()
const appStore = useAppStore()

const loading = ref(false)
const dataSource = ref<RepairCategory[]>([])

// 弹窗相关
const modalVisible = ref(false)
const submitLoading = ref(false)
const isEdit = ref(false)
const editId = ref<number>()

// 表单
const formRef = ref<FormInstance>()
const form = reactive<RepairCategoryAddRequest>({
  categoryName: '',
  description: '',
  isActive: 1
})

// 搜索表单
const searchForm = reactive<RepairCategoryQueryRequest>({
  categoryName: '',
  isActive: undefined as number | undefined,
  pageSize: 10,
  current: 1,
  lastId: 0
})

// 分页状态管理
const paginationState = ref<PaginationState>({
  current: 1,
  pageSize: 10,
  total: 0,
  pages: 0,
  hasNext: false,
  nextCursor: 0,
  previousPageCursors: []
})

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number, range: [number, number]) =>
    `第 ${range[0]}-${range[1]} 条，共 ${total} 条`
})

// 当前页面的起始lastId
const currentPageLastId = ref(0)

// 表格列配置
const columns = [
  {
    title: 'ID',
    dataIndex: 'id',
    key: 'id',
    width: 80
  },
  {
    title: '类别名称',
    dataIndex: 'categoryName',
    key: 'categoryName',
    width: 150
  },
  {
    title: '类别描述',
    dataIndex: 'description',
    key: 'description',
    ellipsis: true
  },
  {
    title: '状态',
    dataIndex: 'isActive',
    key: 'isActive',
    width: 100
  },
  {
    title: '创建时间',
    dataIndex: 'createdAt',
    key: 'createdAt',
    width: 120
  },
  {
    title: '操作',
    key: 'action',
    width: 150,
    fixed: 'right' as const
  }
]

// 表单验证规则
const rules: Record<string, Rule[]> = {
  categoryName: [
    { required: true, message: '请输入类别名称', trigger: 'blur' },
    { min: 2, max: 50, message: '类别名称长度为2-50个字符', trigger: 'blur' }
  ],
  description: [
    { max: 200, message: '描述不能超过200个字符', trigger: 'blur' }
  ]
}

// 格式化日期
const formatDate = (dateString: string) => {
  return new Date(dateString).toLocaleDateString()
}

// 获取类别列表
const fetchData = async (resetPagination = false, useLastId?: number) => {
  try {
    loading.value = true

    if (resetPagination) {
      // 重置分页状态
      paginationState.value = {
        current: 1,
        pageSize: searchForm.pageSize || 10,
        total: 0,
        pages: 0,
        hasNext: false,
        nextCursor: 0,
        previousPageCursors: []
      }
      currentPageLastId.value = 0
    }

    const queryParams = { ...searchForm }
    queryParams.pageSize = paginationState.value.pageSize
    queryParams.current = paginationState.value.current
    queryParams.lastId = useLastId !== undefined ? useLastId : currentPageLastId.value

    const response = await getCategoryList(queryParams)
    if (response.code === 0 && response.data) {
      const pageData = response.data as PageResponse<RepairCategory>

      // 更新数据源
      dataSource.value = pageData.records || []

      // 更新分页状态
      paginationState.value = {
        current: pageData.current,
        pageSize: pageData.size,
        total: pageData.total,
        pages: pageData.pages,
        hasNext: pageData.hasNext,
        nextCursor: pageData.nextCursor,
        previousPageCursors: paginationState.value.previousPageCursors
      }

      // 更新分页配置
      const paginationConfig = createPaginationFromResponse(pageData)
      Object.assign(pagination, paginationConfig)
    }
  } catch (error) {
    console.error('获取类别列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  fetchData(true)
}

// 重置搜索
const resetSearch = () => {
  searchForm.categoryName = ''
  searchForm.isActive = undefined
  fetchData(true)
}

// 表格变化处理
const handleTableChange = (pag: any) => {
  const isNextPage = pag.current > paginationState.value.current
  const isPrevPage = pag.current < paginationState.value.current

  // 更新页面大小
  if (pag.pageSize !== paginationState.value.pageSize) {
    searchForm.pageSize = pag.pageSize
    paginationState.value.pageSize = pag.pageSize
    fetchData(true) // 页面大小变化时重置分页
    return
  }

  if (isNextPage && paginationState.value.hasNext) {
    // 向前翻页
    const navResult = handlePaginationNavigation(
      paginationState.value,
      'next',
      currentPageLastId.value
    )

    paginationState.value.current = navResult.current
    paginationState.value.previousPageCursors = navResult.previousCursors
    currentPageLastId.value = navResult.lastId

    fetchData(false, navResult.lastId)
  } else if (isPrevPage && paginationState.value.current > 1) {
    // 向后翻页
    const navResult = handlePaginationNavigation(
      paginationState.value,
      'prev',
      currentPageLastId.value
    )

    paginationState.value.current = navResult.current
    paginationState.value.previousPageCursors = navResult.previousCursors
    currentPageLastId.value = navResult.lastId

    fetchData(false, navResult.lastId)
  }
}

// 显示新增弹窗
const showCreateModal = () => {
  isEdit.value = false
  editId.value = undefined
  formRef.value?.resetFields()
  form.categoryName = ''
  form.description = ''
  form.isActive = 1
  modalVisible.value = true
}

// 显示编辑弹窗
const showEditModal = (record: RepairCategory) => {
  isEdit.value = true
  editId.value = record.id
  form.categoryName = record.categoryName
  form.description = record.description
  form.isActive = record.isActive
  modalVisible.value = true
}

// 提交表单
const handleSubmit = async () => {
  try {
    await formRef.value?.validate()
    submitLoading.value = true

    if (isEdit.value) {
      // 编辑
      const updateData: RepairCategoryUpdateRequest = {
        id: editId.value!,
        categoryName: form.categoryName,
        description: form.description,
        isActive: form.isActive
      }
      const response = await updateCategory(updateData)
      if (response.code === 0) {
        message.success(response.message || '类别更新成功')
        modalVisible.value = false
        fetchData()
      } else {
        message.error(response.message || '更新失败')
      }
    } else {
      // 新增
      const response = await createCategory(form)
      if (response.code === 0) {
        message.success(response.message || '类别创建成功')
        modalVisible.value = false
        fetchData()
      } else {
        message.error(response.message || '创建失败')
      }
    }
  } catch (error: any) {
    console.error('操作失败:', error)
    if (error?.response?.data?.message) {
      message.error(error.response.data.message)
    } else if (error?.message) {
      message.error(error.message)
    } else {
      message.error('操作失败，请重试')
    }
  } finally {
    submitLoading.value = false
  }
}

// 删除类别
const handleDelete = (record: RepairCategory) => {
  Modal.confirm({
    title: '确认删除',
    content: `确定要删除类别 "${record.categoryName}" 吗？此操作不可恢复。`,
    okText: '确定',
    cancelText: '取消',
    onOk: async () => {
      try {
        const response = await deleteCategory({ id: record.id })
        if (response.code === 0) {
          message.success('删除成功')
          fetchData()
        }
      } catch (error) {
        console.error('删除类别失败:', error)
      }
    }
  })
}

onMounted(() => {
  // 检查权限
  if (!userStore.isAdmin) {
    message.error('没有权限访问此页面')
    return
  }

  // 设置面包屑
  appStore.setBreadcrumbs([
    { title: '首页', path: '/dashboard' },
    { title: '维修类别' },
    { title: '类别管理' }
  ])

  fetchData()
})
</script>

<style scoped>
.category-list {
  padding: 0;
}
</style>
